package com.example.zfb_website.controller;

import com.example.zfb_website.common.utils.AliPayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @description: 支付宝网站支付业务层
 * @author: qiu bo yang
 * @create: 2020-08-14 09:43
 */
@Slf4j
@RequestMapping("/zfb")
@RestController
public class AliPayController {
    //编码格式
    private static final String CHARSET = "UTF-8";

    /**
     * 发起支付宝网站支付
     *
     * @param request
     * @param response
     */
    @PostMapping("/send")
    public void send(HttpServletRequest request, HttpServletResponse response) {
        try {
            //订单号唯一
            String outTradeNo = System.currentTimeMillis() + "";
            String money = request.getParameter("money");
            String subject = request.getParameter("subject");
            String result = AliPayUtils.sendAliPayOrder(outTradeNo, money, subject);
            response.setContentType("text/html;charset=" + CHARSET);
            if (result != null) {
                //直接将完整的表单html输出到页面
                response.getWriter().write(result);
                response.getWriter().flush();
                response.getWriter().close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 支付宝回调地址
     *
     * @param request
     * @param response
     */
    @PostMapping("/notify")
    public void notifyUrl(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取支付宝反馈信息
            Map<String, String> map = AliPayUtils.getPayBackFormat(request);
            // 签名验证
            boolean sign = AliPayUtils.verifySign(map);
            // 验签成功，执行商户操作
            if (sign) {
                //支付成功
                if ("TRADE_SUCCESS".equals(map.get("trade_status"))) {
                    //执行业务逻辑
                    log.info("执行业务逻辑");
                    response.getWriter().write("success");
                }
            } else {
                response.getWriter().write("failure");
            }
            //返回支付宝回调结果
            response.setContentType("text/html;charset=" + CHARSET);
            response.getWriter().flush();
            response.getWriter().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
